package com.zdkj.subway.check.controller.stationTiecketManager.xianWngCJXXQR.shouRuJS;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zdkj.admin.api.entity.SysUser;
import com.zdkj.common.core.util.R;
import com.zdkj.common.security.annotation.Inner;
import com.zdkj.subway.check.entity.*;
import com.zdkj.subway.check.enums.ResultDetailMsg;
import com.zdkj.subway.check.mapper.*;
import com.zdkj.subway.check.result.Result;
import com.zdkj.subway.check.util.JdbcUtil;
import com.zdkj.subway.check.util.ObejctFieldsValueNotNull;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.time.YearMonth;

/**
 * 线网下的收入结算自动提交
 */
@RequestMapping("/xw_js_autosubmit")
@RestController
@Slf4j
public class Xw_shouJieSuanAutoSubmitCtrl {

	@Resource
    SwPmLongPeriodSettlementMapper swPmLongPeriodSettlementMapper;

    @Resource
    SwStMarketingTicketGroupSellMapper swStMarketingTicketGroupSellMapper;
    @Resource
    SwStMarketingTicketOffineTakeTicketMapper swStMarketingTicketOffineTakeTicketMapper;
    
	@Resource
	SwStInternetTicketEquipmentDetailsMapper swStInternetTicketEquipmentDetailsMapper;
	@Resource
	SwAuInternetTicketEquipmentMapper swAuInternetTicketEquipmentMapper;
      
    @Resource
    SysUserMapper sysUserMapper;
  
	@Resource
	Xw_TVM_shouJieSuanCtrl xw_TVM_shouJieSuanCtrl;
	@Resource
	Xw_BOM_shouJieSuanCtrl xw_bom_shouJieSuanCtrl;

	
	private static final Logger LOGGER = LoggerFactory.getLogger(Xw_shouJieSuanAutoSubmitCtrl.class);

	/**
	 * 定时任务执行收入结算自动提交TVM和BOM
	 * @return
	 */
    @ApiOperation(value = "定时任务执行收入结算自动提交TVM和BOM", notes = "每天早晨6点定时提交结算周期范围内的TVM数据以及当天的BOM数据")
    @Inner
    @PostMapping("/autoSubmitTvm")
	public R autoSubmitTvmAndBom() {
		log.info("收入结算自动提交执行于:{}", LocalDateTime.now());
		String sql = "select a.line_code,a.code,c.settlement_term  from sw_param_line b,"+
			         " sw_param_station a left join sw_pm_long_period_settlement c on  a.line_code=c.line_code and a.code=c.station_code  "+
			         " where a.line_code=b.code and a.del_flag=0 and b.del_flag=0  and (b.serviceid='1' or b.code='16') "+
			         " order by a.line_code,a.code";
        try {
			
			/* 自动提交功能屏蔽 20250105 
			List<Map<String, Object>> listStations= JdbcUtil.exeSqlQueryByCon(sql);
			if(listStations!=null && listStations.size()>0){
			
				for(int i=0;i<listStations.size();i++){
					Map<String,Object> map = listStations.get(i);
					String lineCode = (String)map.get("line_code");
					String stationCode = (String)map.get("code");
					//LOGGER.error("自动提交BOM3333，所属的线路为："+lineCode+",所属的车站为："+stationCode+" ,时间为："+LocalDateTime.now());

					boolean isLong = map.get("settlement_term")!=null;//isLongPeriod(lineCode,stationCode);  减少一次查询

					//LOGGER.info("自动提交获取长周期，所属的线路为："+lineCode+",所属的车站为："+stationCode+" ,时间为："+LocalDateTime.now()+isLong);
					//将正在执行自动化任务的开关打开
					TvmUtil.initAutoSubmitFlag(lineCode,stationCode,"1");
					boolean isTvmOk = submitTvm(lineCode,stationCode,isLong);	
					//LOGGER.info("自动提交TVM是否成功  "+lineCode+",所属的车站为："+stationCode+" ,时间为："+LocalDateTime.now()+isTvmOk);
					boolean isBomOk = submitBom(lineCode,stationCode,isLong);
					
					LOGGER.info("自动提交BOM是否成功---，所属的线路为："+lineCode+",所属的车站为："+stationCode+" ,时间为："+LocalDateTime.now()+isBomOk);
					
					if(!isTvmOk){						
						LOGGER.error("自动提交TVM失败，所属的线路为："+lineCode+",所属的车站为："+stationCode+" ,时间为："+LocalDateTime.now());
					}
					
					if(!isBomOk){						
						LOGGER.error("自动提交BOM失败，所属的线路为："+lineCode+",所属的车站为："+stationCode+" ,时间为："+LocalDateTime.now());
					}
					//开关关闭
					TvmUtil.initAutoSubmitFlag(lineCode,stationCode,"0");
				}			
				
			}*/
            //更新 ck_data_submit   todo    自动CK_Data，需要放到生产 后再把此功能放開
			autoSubmitCkData();
			//自动提交 互联网售票机  20240204去掉互联网售票机操作
			//autoSubmitInternet();
			log.info("收入结算自动提交结束于:{}", LocalDateTime.now());


			
		} catch (Exception  e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
        return R.ok();
    }


	/**
	 * 自动提交tvm
	 * @param lineCode
	 * @param stationCode
	 * @param isLong
	 * @return
	 */
	private boolean submitTvm(String lineCode,String stationCode,boolean isLong ){
		boolean isOk = true;
		try{
			//将要提交的数据日期范围
			Map<String, Object> mapSettleDate =get_sw_ck_data_submit_date(lineCode,stationCode);
			if(mapSettleDate ==null){
				return true;  //未找到车站结算周期数据
			}
			String startSettleDate=String.valueOf(mapSettleDate.get("startSettleDate"));
			String endSettleDate=String.valueOf(mapSettleDate.get("endSettleDate"));
            startSettleDate=startSettleDate.substring(0,startSettleDate.length()-2);
			endSettleDate=endSettleDate.substring(0,endSettleDate.length()-2);
			//比如提交10号数据，endSettleDate 返回11号 01:59:59秒，当前日期是11号
			if(!getDate().equals(endSettleDate.substring(0,10))){//未到结算周期内的时间,不自动提交
				if(isFirstDayofMonth(Calendar.getInstance())){//月初第一天
						endSettleDate = getDate();
				}else {
							//continue;
					return true;  //未到结算日，不做提交
				}
			 }
             //查询待提交数据
             String is_not_settle_status="2";
             String approvalStatus = "0";
             Map<String,String> queryParam = new HashMap();
			 queryParam.put("lineCode",lineCode);
			 queryParam.put("stationCode",stationCode);
			 queryParam.put("startSettleDate",startSettleDate);
			 queryParam.put("endSettleDate",endSettleDate);
			 queryParam.put("is_not_settle_status",is_not_settle_status);
			 queryParam.put("approvalStatus",approvalStatus);
                     
			 List<Map<String, Object>> tvm_shouJieSuan_waitSubmit = TvmUtil.getXw_tvm_shouJieSuan_waitSubmit(queryParam);
					
	 		 if(tvm_shouJieSuan_waitSubmit!=null && tvm_shouJieSuan_waitSubmit.size()>0){
						
				boolean isTaskAutoSubmit = true;
			    StringBuilder sbIds = new StringBuilder(); 
				String userCode = "";
				String attendancePersonJobNo = "";						
				for(int j=0;j<tvm_shouJieSuan_waitSubmit.size();j++){
					 Map<String, Object> mapWait = tvm_shouJieSuan_waitSubmit.get(j);
					 if(mapWait.get("beginSettleDate")!=null){
							   mapWait.put("beginSettleDate",String.valueOf(mapWait.get("beginSettleDate")).substring(0,19));
					  }
					if(mapWait.get("settleDate")!=null){
						   mapWait.put("settleDate",String.valueOf(mapWait.get("settleDate")).substring(0,19));
					 }
					 if(mapWait.get("endSettleDate")!=null){
					       mapWait.put("endSettleDate",String.valueOf(mapWait.get("endSettleDate")).substring(0,19));
					 }
					 mapWait.put("js_endSettleDate",String.valueOf(mapWait.get("js_endSettleDate")).substring(0,19));
                     String id = String.valueOf(mapWait.get("id"));
					 if(sbIds.length()!=0){
					     sbIds.append(",");
					 }
					 sbIds.append(id);
					 userCode = String.valueOf(mapWait.get("userCode"));
					 attendancePersonJobNo =  String.valueOf(mapWait.get("attendancePersonJobNo"));				   
				}
                Map<String,Object> autoSubmitParam = new HashMap();
				autoSubmitParam.put("ids",sbIds.toString());
				autoSubmitParam.put("rows",JSONObject.toJSONString(tvm_shouJieSuan_waitSubmit));
				autoSubmitParam.put("attendancePersonJobNo",attendancePersonJobNo);
				autoSubmitParam.put("userCode",userCode);//模拟当前登录人                        
				autoSubmitParam.put("lineCode",lineCode);
				autoSubmitParam.put("stationCode",stationCode);
				autoSubmitParam.put("startSettleDate",startSettleDate);
				autoSubmitParam.put("endSettleDate",endSettleDate);
				autoSubmitParam.put("isLong",isLong);
				autoSubmitParam.put("isTaskAutoSubmit",isTaskAutoSubmit);
				xw_TVM_shouJieSuanCtrl.submit_Xw_tvm_data(new JSONObject(autoSubmitParam));

			 }//end if 是否有待提交数据
		
		}catch(Exception e){
		   e.printStackTrace();
		   isOk = false;
		}
		return isOk;

	
	}

	/**
	 * 自动提交bom
	 * @param lineCode
	 * @param stationCode
	 * @param isLong
	 * @return
	 */
	private boolean submitBom(String lineCode,String stationCode,boolean isLong ){
		boolean isOk = true;
		try{
			//售票员一天一结算，不用判断是否长周期，开始日期当前日期前一天两点，到当天日期的01:59:59秒
			String startSettleDate = getBeforeDate()+" 02:00:00";
			String endSettleDate = getDate()+" 01:59:59";
            String is_not_settle_status="2";
            String approvalStatus = "0";
			String is_add_report_error = "0";
            
            Map<String,String> queryParam = new HashMap();
			 queryParam.put("lineCode",lineCode);
			 queryParam.put("stationCode",stationCode);
			 queryParam.put("startSettleDate",startSettleDate);
			 queryParam.put("endSettleDate",endSettleDate);
			 queryParam.put("is_not_settle_status",is_not_settle_status);
			 queryParam.put("isAddReportError",is_add_report_error);
			 //获取tvm分钱箱清点记录里面的清点金额，补币金额
		    List<Map<String,Object>> bom_shouJieSuan_waitSubmit=BomUtil.getXw_bom_shouJieSuan_waitSubmit(queryParam);
			if(bom_shouJieSuan_waitSubmit!=null && bom_shouJieSuan_waitSubmit.size()>0){
			
			    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

				StringBuilder sbIds = new StringBuilder();
				String userCode = "";
				String attendancePersonJobNo = "001";//赋值admin

				for(Map<String,Object> map:bom_shouJieSuan_waitSubmit){

					String id = String.valueOf(map.get("id"));
					if(sbIds.length()!=0){
						sbIds.append(",");
					}
					sbIds.append(id);
					userCode = String.valueOf(map.get("userCode"));
					attendancePersonJobNo =  String.valueOf(map.get("attendancePersonJobNo"));


					Object smtId = map.get("smtId");
					BigDecimal electronicAmount=new BigDecimal(0);//电子金额
					map.put("workingStartTime",String.valueOf(map.get("workingStartTime")).substring(0,19));
					map.put("workingEndTime",String.valueOf(map.get("workingEndTime")).substring(0,19));
					map.put("js_endSettleDate",String.valueOf(map.get("js_endSettleDate")).substring(0,19));
					map.put("settleTime",simpleDateFormat.format(map.get("settleTime")));
					QueryWrapper<SwStMarketingTicketGroupSell> swStMarketingTicketGroupSellQueryWrapper=new QueryWrapper<>();
					swStMarketingTicketGroupSellQueryWrapper.select("ifnull(sum(discount_amount),0) discount_amount");
					swStMarketingTicketGroupSellQueryWrapper.eq("relation_id",smtId);
					swStMarketingTicketGroupSellQueryWrapper.eq("del_flag",0);
					String[] pay_method={"1","2","3"}; //微信，现金，银行
					swStMarketingTicketGroupSellQueryWrapper.in("pay_method",pay_method);
					List<Map<String, Object>> maps = swStMarketingTicketGroupSellMapper.selectMaps(swStMarketingTicketGroupSellQueryWrapper);//团购的
					if(maps!=null && maps.size()>0){
						Map<String, Object> res = maps.get(0);
						BigDecimal discount_amount = (BigDecimal)res.get("discount_amount");
						electronicAmount=electronicAmount.add(discount_amount);
					}

					/* 这个取的问题，合计总数包括了现金,而且现在也不录入微信和支付宝了

					QueryWrapper<SwStMarketingTicketOffineSell> swStMarketingTicketOffineSellQueryWrapper=new QueryWrapper<>();
					swStMarketingTicketOffineSellQueryWrapper.select("ifnull(sum(alipay_sell_amount),0) alipay_sell_amount",
							"ifnull(sum(wechat_sell_amount),0) wechat_sell_amount");
					swStMarketingTicketOffineSellQueryWrapper.eq("relation_id",smtId);
					swStMarketingTicketOffineSellQueryWrapper.eq("del_flag",0);
					BigDecimal alipayAndwechat=new BigDecimal(0);
					List<Map<String, Object>> map2 = swStMarketingTicketOffineSellMapper.selectMaps(swStMarketingTicketOffineSellQueryWrapper);//正常取得，微信，支付宝
					if(map2!=null && map2.size()>0){
						Map<String, Object> res = map2.get(0);
						BigDecimal alipay_sell_amount = (BigDecimal)res.get("alipay_sell_amount");
						BigDecimal wechat_sell_amount = (BigDecimal)res.get("wechat_sell_amount");
						alipayAndwechat=alipayAndwechat.add(alipay_sell_amount).add(wechat_sell_amount);
					}*/
					
					QueryWrapper<SwStMarketingTicketOffineTakeTicket> swStMarketingTicketOffineTakeTicketQueryWrapper=new QueryWrapper<>();
					swStMarketingTicketOffineTakeTicketQueryWrapper.select("ifnull(sum(sell_amount),0) sell_amount");
					swStMarketingTicketOffineTakeTicketQueryWrapper.eq("relation_id",smtId);
					swStMarketingTicketOffineTakeTicketQueryWrapper.eq("del_flag",0);
					BigDecimal sell=new BigDecimal(0);
					List<Map<String, Object>> map3 = swStMarketingTicketOffineTakeTicketMapper.selectMaps(swStMarketingTicketOffineTakeTicketQueryWrapper);//线下取票
					if(map3!=null && map3.size()>0){
						Map<String, Object> res = map3.get(0);
						BigDecimal sell_amount = (BigDecimal)res.get("sell_amount");
						sell=sell.add(sell_amount);
					}

					electronicAmount=electronicAmount.add(sell);//.alipayAndwechat
					map.put("electronicAmount",electronicAmount);

				}//end for
				
				boolean isTaskAutoSubmit = true;

			   Map<String,Object> autoSubmitParam = new HashMap();
					 autoSubmitParam.put("ids",sbIds.toString());
					 autoSubmitParam.put("params",JSONObject.toJSONString(bom_shouJieSuan_waitSubmit));
					 autoSubmitParam.put("attendancePersonJobNo",attendancePersonJobNo);
					 autoSubmitParam.put("userCode",userCode);//模拟当前登录人                        
					 autoSubmitParam.put("lineCode",lineCode);
					 autoSubmitParam.put("stationCode",stationCode);
					 autoSubmitParam.put("startTime",startSettleDate);
					 autoSubmitParam.put("endTime",endSettleDate);
					 autoSubmitParam.put("isLong",isLong);
					 autoSubmitParam.put("isTaskAutoSubmit",isTaskAutoSubmit);						 
					 xw_bom_shouJieSuanCtrl.bomSubmitTvmData(new JSONObject(autoSubmitParam));

			}			
		
		}catch(Exception e){
		   e.printStackTrace();
		   isOk = false;
		}
		return isOk;

	
	}

	/**
	 * 更新结算周期表,是否放到收入结算一起提交，
	 * 待定，这个更新时间过早，9点前车站可能也会提交数据
	 * @return
	 */
	private boolean autoSubmitCkData(){
		
		boolean isOk = true;
		
		StringBuilder sb = new StringBuilder();
        StringBuilder sbnew = new StringBuilder();
		StringBuilder sbAdd = new StringBuilder();
		sbAdd.append("insert into subway.sw_ck_data_submit_log ")
             .append("(RELATION_ID,LINE_CODE,STATION_CODE,BEGIN_TIME,END_TIME,SETTLEMENT_TERM,SUBMIT_TIME) ")
             .append(" select a.ID,a.LINE_CODE,a.STATION_CODE,a.BEGIN_TIME,a.END_TIME,st.SETTLEMENT_TERM,now() ")
             .append(" from subway.sw_ck_data_submit a,(  ")
		     .append(" select a.LINE_CODE,a.CODE,ifnull(b.TVM_SETTLEMENT_TERM,1) TVM_SETTLEMENT_TERM,ifnull(b.BOM_SETTLEMENT_TERM,1) BOM_SETTLEMENT_TERM,ifnull(b.SETTLEMENT_TERM,1) SETTLEMENT_TERM  ")
		     .append(" from subway.sw_param_station a ")
		     .append(" left join (select * from subway.sw_pm_long_period_settlement where DEL_FLAG = '0') b on a.LINE_CODE = b.LINE_CODE  and a.CODE = b.STATION_CODE ")
             .append(") st ")
             .append(" where a.LINE_CODE = st.LINE_CODE and a.STATION_CODE = st.CODE AND DATE_FORMAT(a.SUBMIT_TIME,'%Y-%m-%d') = DATE_FORMAT(now(),'%Y-%m-%d')");
		
		if(isFirstDayofMonth(Calendar.getInstance())){//月初第一天
		    sb.append("update subway.sw_ck_data_submit a ")
			  .append("set a.BEGIN_TIME=date_add(a.END_TIME,interval 1 second),a.END_TIME=date_format(now(),'%Y-%m-%d 01:59:59'),a.SUBMIT_TIME=now();"); 
		    
			sbnew.append("insert into subway.sw_ck_data_submit ")
            .append("( LINE_CODE,STATION_CODE,BEGIN_TIME,END_TIME,STATUS,SUBMIT_PERSON_ID,SUBMIT_PERSON_CODE,SUBMIT_PERSON_NAME,SUBMIT_TIME," +
                    "CREATOR_ID,CREATOR_NAME,CREATE_TIME)")
            .append("select st.LINE_CODE,st.CODE,")
            .append("ifnull(date_add(a.END_TIME,interval 1 second),date_format(date_add(now(),interval -1 day),'%Y-%m-%d 02:00:00')),date_format(now(),'%Y-%m-%d 01:59:59'),")
            .append("1,0,'0','',now(),0,'',now() ")
            .append("from ")
            .append("(select a.LINE_CODE,a.CODE,ifnull(b.TVM_SETTLEMENT_TERM,1) TVM_SETTLEMENT_TERM,ifnull(b.BOM_SETTLEMENT_TERM,1) BOM_SETTLEMENT_TERM,ifnull(b.SETTLEMENT_TERM,1) SETTLEMENT_TERM " +
                            "from subway.sw_param_station a left join (select * from subway.sw_pm_long_period_settlement where DEL_FLAG = '0') b on a.LINE_CODE = b.LINE_CODE  and a.CODE = b.STATION_CODE " +
                    "where concat(Lpad(a.LINE_CODE,2,'0'),Lpad(a.CODE,2,'0')) not in (select concat(Lpad(LINE_CODE,2,'0'),Lpad(STATION_CODE,2,'0')  ) from subway.sw_ck_data_submit) " +
                    " and  a.LINE_CODE in(select code from sw_param_line where serviceid='1' or code='16') )")  //追加不是西安地铁线路和站点的新增--todo test
            .append(" st ")
            .append("left join subway.sw_ck_data_submit a on st.LINE_CODE = a.LINE_CODE and st.CODE=a.STATION_CODE;");	
		}else{
		  sb.append("update subway.sw_ck_data_submit a,(")
		  .append(" select a.LINE_CODE,a.CODE,ifnull(b.TVM_SETTLEMENT_TERM,1) TVM_SETTLEMENT_TERM,ifnull(b.BOM_SETTLEMENT_TERM,1) BOM_SETTLEMENT_TERM,ifnull(b.SETTLEMENT_TERM,1) SETTLEMENT_TERM ")
		  .append("from subway.sw_param_station a ")
		  .append("left join (select * from subway.sw_pm_long_period_settlement where DEL_FLAG = '0') b on a.LINE_CODE = b.LINE_CODE  and a.CODE = b.STATION_CODE ")
          .append(") st ")
          .append("set a.BEGIN_TIME=date_add(a.END_TIME,interval 1 second),a.END_TIME=date_add(a.END_TIME,interval st.SETTLEMENT_TERM day),")
          .append("SUBMIT_TIME = now() ")
          .append("where a.LINE_CODE = st.LINE_CODE and a.STATION_CODE = st.CODE and datediff(now(),a.END_TIME)=st.SETTLEMENT_TERM;");
        sbnew.append("insert into subway.sw_ck_data_submit ")
            .append("( LINE_CODE,STATION_CODE,BEGIN_TIME,END_TIME,STATUS,SUBMIT_PERSON_ID,SUBMIT_PERSON_CODE,SUBMIT_PERSON_NAME,SUBMIT_TIME," +
                    "CREATOR_ID,CREATOR_NAME,CREATE_TIME)")
            .append("select st.LINE_CODE,st.CODE,")
            .append("ifnull(date_add(a.END_TIME,interval 1 second),date_format(date_add(now(),interval -1 day),'%Y-%m-%d 02:00:00')),ifnull(date_add(a.BEGIN_TIME,interval st.SETTLEMENT_TERM day),date_format(now(),'%Y-%m-%d 01:59:59')),")
            .append("1,0,'0','',now(),0,'',now() ")
            .append("from ")
            .append("(select a.LINE_CODE,a.CODE,ifnull(b.TVM_SETTLEMENT_TERM,1) TVM_SETTLEMENT_TERM,ifnull(b.BOM_SETTLEMENT_TERM,1) BOM_SETTLEMENT_TERM,ifnull(b.SETTLEMENT_TERM,1) SETTLEMENT_TERM " +
                            "from subway.sw_param_station a left join (select * from subway.sw_pm_long_period_settlement where DEL_FLAG = '0') b on a.LINE_CODE = b.LINE_CODE  and a.CODE = b.STATION_CODE " +
                    "where concat(Lpad(a.LINE_CODE,2,'0'),Lpad(a.CODE,2,'0')) not in (select concat(Lpad(LINE_CODE,2,'0'),Lpad(STATION_CODE,2,'0') ) from subway.sw_ck_data_submit) " +
                    "and  a.LINE_CODE in(select code from sw_param_line where serviceid='1' or code='16'))")  //追加不是西安地铁线路和站点的新增  -todo test
            .append(" st ")
            .append("left join subway.sw_ck_data_submit a on st.LINE_CODE = a.LINE_CODE and st.CODE=a.STATION_CODE;");
		}		
		
		
		try {
            int iResult = JdbcUtil.exeSqlCrud(sb.toString());
            int iResult2 = JdbcUtil.exeSqlCrud(sbnew.toString());
			int iResultAdd = JdbcUtil.exeSqlCrud(sbAdd.toString());
            //R result = remoteSubwayStmService.calcBomSettle(SecurityConstants.FROM_IN);
			//20250318增加长周期结算设置表的操作
			 /**
     获取结算周期设置表的参数设置  默认值：10  一般临时值：11  2月闰月临时值：9  2月普通临时值：8 
	 LONGPERIOD_SETTING 字典标识
       label：defaultValue  value:10  默认值
       tmpValue   value:11             一般临时值
       twoDefaultValue  value 8  2月普通临时值
       twoTmpValue   Value 9     2月闰月临时值
   */
            Map<String,String> mapLongperiod = getLongPeriodDict();
			if(mapLongperiod!=null && mapLongperiod.size()>0){
				String defaultValue = mapLongperiod.get("defaultValue");
				String tmpValue = mapLongperiod.get("tmpValue");
				String twoDefaultValue = mapLongperiod.get("twoDefaultValue");
				String twoTmpValue = mapLongperiod.get("twoTmpValue");
                //如果默认值是10日结算才设置如下规则
				if("10".equals(defaultValue)){
					int currentDay = getCurrentDay(Calendar.getInstance());
					int monthDays = getCurrentMonthDays();
					String sqlResetLongperiod ="";
					//21号根据当前设置，更新结算周期时间，为下一周期的结算做准备
					if(currentDay==21){						
						if(monthDays==31){
							sqlResetLongperiod = "update sw_pm_long_period_settlement set SETTLEMENT_TERM="+tmpValue+",TVM_SETTLEMENT_TERM='"+tmpValue+"',BOM_SETTLEMENT_TERM='"+tmpValue+"'";
						}
						if(monthDays==28){
							sqlResetLongperiod = "update sw_pm_long_period_settlement set SETTLEMENT_TERM="+twoDefaultValue+",TVM_SETTLEMENT_TERM='"+twoDefaultValue+"',BOM_SETTLEMENT_TERM='"+twoDefaultValue+"'";
						}
						if(monthDays==29){
							sqlResetLongperiod = "update sw_pm_long_period_settlement set SETTLEMENT_TERM="+twoTmpValue+",TVM_SETTLEMENT_TERM='"+tmpValue+"',BOM_SETTLEMENT_TERM='"+tmpValue+"'";
						}
					}
                    //每月1日，恢复之前的默认设置
					if(currentDay==1){
						sqlResetLongperiod = "update sw_pm_long_period_settlement set SETTLEMENT_TERM="+defaultValue+",TVM_SETTLEMENT_TERM='"+defaultValue+"',BOM_SETTLEMENT_TERM='"+defaultValue+"'";
					}
					if(!"".equals(sqlResetLongperiod)){
						int resultLong = JdbcUtil.exeSqlCrud(sqlResetLongperiod);
						 LOGGER.info("结算周期21号或者1号特殊更新执行于:{}，输出{}", LocalDateTime.now(), sqlResetLongperiod+String.valueOf(resultLong));
					}

					
				}
			}
            LOGGER.info("结算周期更新执行于:{}，输出{}", LocalDateTime.now(), iResult);
        }catch (Exception e) {
        	LOGGER.error("结算周期自动更新失败！",e);
        	isOk = false;
        }
		return isOk;
	}

	/**
	 * 定时任务执行收入结算自动提交互联网售票机
	 * @return
	 */
    @ApiOperation(value = "定时任务执行收入结算自动提交互联网售票机", notes = "每天早晨6点定时提交结算所有未提交的互联网售票机数据")
    @Inner
    @PostMapping("/autoSubmitInternet")
	@Transactional(rollbackFor = Exception.class)
    public R autoSubmitInternet() {
        try {
			SimpleDateFormat dff = new SimpleDateFormat("yyyy-MM-dd");
			List<SwStInternetTicketEquipmentDetails> swStInternetTicketEquipmentDetails = swStInternetTicketEquipmentDetailsMapper.selectList(Wrappers.<SwStInternetTicketEquipmentDetails>lambdaQuery()
					.eq(SwStInternetTicketEquipmentDetails::getApprovalStatus, "0")
					.eq(SwStInternetTicketEquipmentDetails::getDelFlag,"0")
					.eq(SwStInternetTicketEquipmentDetails::getReportModifyStatus, "0"));

			//只查未提交、不是报表差错修改状态的
			//结果集 根据原来的业务，存在修改，不存在新增。---收入审核  人员就是1,admin,管理员
		    //车站的互联网售票机记录同时做状态更新、人员更新  客运人员用创建人信息（没有工号，需要查询下）。人员就是1,admin,管理员存储到值班站长
			if(CollectionUtil.isNotEmpty(swStInternetTicketEquipmentDetails)){

				for(SwStInternetTicketEquipmentDetails swStInternetTicketEquipment:swStInternetTicketEquipmentDetails){
					//收入日期为null 跳过不执行 （垃圾数据，正常操作收入日期不能为null
					if(swStInternetTicketEquipment.getRevenueDate() == null){
						continue;
					}
					//    （修改条件：线路站点、设备编号、收益日期）
					//  不存在insert
					SwAuInternetTicketEquipment swAuInternetTicketEquipment1 = swAuInternetTicketEquipmentMapper.selectOne(
							Wrappers.<SwAuInternetTicketEquipment>lambdaQuery()
									.eq(SwAuInternetTicketEquipment::getLineCode, swStInternetTicketEquipment.getLineCode())
									.eq(SwAuInternetTicketEquipment::getStationCode, swStInternetTicketEquipment.getStationCode())
									.eq(SwAuInternetTicketEquipment::getEquipmentCode, swStInternetTicketEquipment.getEquipmentCode())
									.eq(SwAuInternetTicketEquipment::getDelFlag,"0")
									.eq(SwAuInternetTicketEquipment::getRevenueDate, swStInternetTicketEquipment.getRevenueDate()));

					if(swAuInternetTicketEquipment1 ==null){

						SwAuInternetTicketEquipment swAuInternetTicketEquipment =new SwAuInternetTicketEquipment();
						swAuInternetTicketEquipment.setLineCode(swStInternetTicketEquipment.getLineCode());
						swAuInternetTicketEquipment.setStationCode(swStInternetTicketEquipment.getStationCode());
						swAuInternetTicketEquipment.setStartTime(dff.format(swStInternetTicketEquipment.getStartTime()));
						swAuInternetTicketEquipment.setEndTime(dff.format(swStInternetTicketEquipment.getEndTime()));
						swAuInternetTicketEquipment.setTotalNumberSales(swStInternetTicketEquipment.getSaleNumber());
                        swAuInternetTicketEquipment.setRemark(swStInternetTicketEquipment.getRemark());

						swAuInternetTicketEquipment.setSubtotalTotal(swStInternetTicketEquipment.getTotalSaleAmount());
						long SettlementPeriod=(swStInternetTicketEquipment.getEndTime().getTime()-swStInternetTicketEquipment.getStartTime().getTime())/(24*60*60*1000);
						swAuInternetTicketEquipment.setSettlementPeriod(Integer.parseInt(String.valueOf(SettlementPeriod)));
						swAuInternetTicketEquipment.setApprovalStatus(0);
						swAuInternetTicketEquipment.setIsAddReprotError("0");
						swAuInternetTicketEquipment.setCreatorId(swStInternetTicketEquipment.getCreatorId());
						swAuInternetTicketEquipment.setCreatorName(swStInternetTicketEquipment.getCreatorName());
						swAuInternetTicketEquipment.setCreateTime(new Date());

						SysUser user = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserId, swStInternetTicketEquipment.getCreatorId()));
						if(user!=null){
							swAuInternetTicketEquipment.setPassengerAttendantId(swStInternetTicketEquipment.getCreatorId());
							swAuInternetTicketEquipment.setPassengerAttendantJobNo(user.getUserCode());
							swAuInternetTicketEquipment.setPassengerAttendantName(swStInternetTicketEquipment.getCreatorName());
						}

						swAuInternetTicketEquipment.setEquipmentCode(swStInternetTicketEquipment.getEquipmentCode());
						swAuInternetTicketEquipment.setEquipmentName(swStInternetTicketEquipment.getEquipmentName());
						swAuInternetTicketEquipment.setRevenueDate(dff.format(swStInternetTicketEquipment.getRevenueDate()));
						swAuInternetTicketEquipment.setReportModifyStatus(swStInternetTicketEquipment.getReportModifyStatus());

						swAuInternetTicketEquipment.setAttendancePersonId(1);
						swAuInternetTicketEquipment.setAttendancePersonJobNo("001");
						swAuInternetTicketEquipment.setAttendancePersonName("管理员");

						swAuInternetTicketEquipment =(SwAuInternetTicketEquipment)ObejctFieldsValueNotNull.setValueNoNull(SwAuInternetTicketEquipment.class, swAuInternetTicketEquipment);
						swAuInternetTicketEquipment =(SwAuInternetTicketEquipment)ObejctFieldsValueNotNull.jisuanBigDicmalMulti(SwAuInternetTicketEquipment.class, swAuInternetTicketEquipment,100d);

						swAuInternetTicketEquipmentMapper.insertSwAuInputInternetTicketEquipment(swAuInternetTicketEquipment);

						swStInternetTicketEquipment.setSwAuInternetTicketId(swAuInternetTicketEquipment.getId());
						updateInternetTicketEquipmentDetails(swStInternetTicketEquipment);

					}else {
						//存在就update发售数量，发售金额、差异金额、差异数量
						SwAuInternetTicketEquipment swAuInternetTicketEquipment =new SwAuInternetTicketEquipment();
						swAuInternetTicketEquipment.setId(swAuInternetTicketEquipment1.getId());
						swAuInternetTicketEquipment.setTotalNumberSales(swStInternetTicketEquipment.getSaleNumber());
						swAuInternetTicketEquipment.setSubtotalTotal(swStInternetTicketEquipment.getTotalSaleAmount());
						swAuInternetTicketEquipment.setRemark(swStInternetTicketEquipment.getRemark());
						swAuInternetTicketEquipmentMapper.updateById(swAuInternetTicketEquipment);

						updateInternetTicketEquipmentDetails(swStInternetTicketEquipment);
					}

				}
			}

		 }catch (Exception  e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	  return R.ok();
	}


	/**
	 * 更新互联网售票机详情
	 * @param swStInternetTicketEquipment
	 * @throws Exception
	 */
	private void updateInternetTicketEquipmentDetails(SwStInternetTicketEquipmentDetails swStInternetTicketEquipment) throws Exception {

		SysUser user = sysUserMapper.selectOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUserId, swStInternetTicketEquipment.getCreatorId()));
		if(user!=null){
			swStInternetTicketEquipment.setPassengerAttendantId(swStInternetTicketEquipment.getCreatorId());
			swStInternetTicketEquipment.setPassengerAttendantJobNo(user.getUserCode());
			swStInternetTicketEquipment.setPassengerAttendantName(swStInternetTicketEquipment.getCreatorName());
		}
		swStInternetTicketEquipment.setApprovalStatus(1);
		swStInternetTicketEquipment.setUpdateTime(new Date());


		swStInternetTicketEquipment.setAttendancePersonId(1);
		swStInternetTicketEquipment.setAttendancePersonJobNo("001");
		swStInternetTicketEquipment.setAttendancePersonName("管理员");

		swStInternetTicketEquipmentDetailsMapper.updateById(swStInternetTicketEquipment);
	}

	/**
	 * 获取将要提交的数据日期范围
	 * @param lineCode
	 * @param stationCode
	 * @return
	 * @throws SQLException
	 */
	 private Map<String, Object> get_sw_ck_data_submit_date(String lineCode,String stationCode) throws SQLException {
        Result result=new Result(ResultDetailMsg.OK);
        String sql="select date_add(a.END_TIME,interval 1 second) startSettleDate,date_add(a.END_TIME,interval (ifnull(b.settlement_term,1)) day) endSettleDate\n" +
                " from SW_CK_DATA_SUBMIT a\n" +
                " left join sw_pm_long_period_settlement b on  a.LINE_CODE = b.LINE_CODE  and a.STATION_CODE = b.STATION_CODE and b.DEL_FLAG = '0'\n" +
                " where  a.LINE_CODE = '"+lineCode+"'\n" +
                " and a.STATION_CODE = '"+stationCode+"'";
        List<Map<String, Object>> res = JdbcUtil.exeSqlQuery(sql);
        if(res!=null && res.size()>0){
		   return res.get(0);
		}
        return null;
    }
	private Map<String, Object> get_real_sw_ck_data_submit_date(String lineCode,String stationCode) throws SQLException {
		Result result=new Result(ResultDetailMsg.OK);
		String sql="select a.BEGIN_TIME startSettleDate, a.END_TIME endSettleDate\n" +
				" from SW_CK_DATA_SUBMIT a\n" +
				" where  a.LINE_CODE = '"+lineCode+"'\n" +
				" and a.STATION_CODE = '"+stationCode+"'";
		List<Map<String, Object>> res = JdbcUtil.exeSqlQuery(sql);
		if(res!=null && res.size()>0){
			return res.get(0);
		}
		return null;
	}

	
	
	
    private  boolean isLongPeriod(String lineCode,String stationCode){
	     Map<String,Object> param=new HashMap<>();
		if(StringUtils.isNotEmpty(lineCode)){
            param.put("line_code",lineCode);
        }
        if(StringUtils.isNotEmpty(stationCode)){
            param.put("station_code",stationCode);
        }
        List<SwPmLongPeriodSettlement> swPmLongPeriodSettlements = swPmLongPeriodSettlementMapper.selectByMap(param);
        if(swPmLongPeriodSettlements!=null && swPmLongPeriodSettlements.size()>0){
            return true;
		}
		return false;
	}
	private  static String getNextDate(){
       	Date date = new Date();
		Calendar   calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(calendar.DATE,1); //把日期往后增加一天,整数  往后推,负数往前移动
		date=calendar.getTime();
	   	SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
	   	String timeStr = sf.format(date);
	   	return timeStr;
    }

	/**
	 * 获取前一天日期
	 * @return
	 */
	private  static String getBeforeDate(){
		Date date = new Date();
		Calendar   calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(calendar.DATE,-1); //把日期负数往前移动
		date=calendar.getTime();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String timeStr = sf.format(date);
		return timeStr;
	}

	/**
	 * 获取当前日期
	 * @return
	 */
	private  static String getDate(){
		Date date = new Date();
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		String timeStr = sf.format(date);
		return timeStr;
	}

	/**
	 * 判断是否是月初第一天
	 * @param calendar
	 * @return
	 */
	private static boolean isFirstDayofMonth(Calendar calendar){
		if (calendar == null) {
			throw new IllegalArgumentException("Calendar cannot be null.");
		}

		int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		return dayOfMonth == 1;
	}
	/**
	 * 获取当前日
	 * @param calendar
	 * @return
	 */
	private static int getCurrentDay(Calendar calendar){
		if (calendar == null) {
			throw new IllegalArgumentException("Calendar cannot be null.");
		}

		int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
		return dayOfMonth;
	}

	/**
	 * 判断当前月有多少天
	*/
	private static int getCurrentMonthDays(){
		
		// 获取当前年份和月份
        YearMonth yearMonth = YearMonth.now();
        
        // 获取该月份的天数
        int daysInMonth = yearMonth.lengthOfMonth();
		return daysInMonth;
	}
   /**
     获取结算周期设置表的参数设置  默认值：10  一般临时值：11  2月闰月临时值：9  2月普通临时值：8 
	 LONGPERIOD_SETTING 字典标识
       label：defaultValue  value:10  默认值
       tmpValue   value:11             一般临时值
       twoDefaultValue  value 8  2月普通临时值
       twoTmpValue   Value 9     2月闰月临时值
   */
   private static Map<String,String> getLongPeriodDict(){
		Map<String,String> map = new HashMap();
		try{
			String sql  = "select label,value from sys_dict_item where type='LONGPERIOD_SETTING' and del_flag='0' ";
			List<Map<String, Object>> listPeriod= JdbcUtil.exeSqlQueryByCon(sql);
			if(listPeriod!=null && listPeriod.size()>0){
				for(int i=0;i<listPeriod.size();i++){
					Map<String,Object> mapSingle = listPeriod.get(i);
					String label = String.valueOf(mapSingle.get("label"));
					String value = String.valueOf(mapSingle.get("value"));
					map.put(label,value);
				}
				return map;
			}

		}catch(Exception e){
			
		}
		return map;
	}

}
